package com.zhuhjay.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuhjay.eduservice.entity.EduSubject;
import com.zhuhjay.eduservice.entity.excel.SubjectData;
import com.zhuhjay.eduservice.entity.subject.SubjectItem;
import com.zhuhjay.eduservice.listener.SubjectExcelListener;
import com.zhuhjay.eduservice.mapper.EduSubjectMapper;
import com.zhuhjay.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.servicebase.exception.GuLiException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ZhuHJay
 * @since 2022-09-06
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Override
    public void saveSubject(MultipartFile file) {
        try (InputStream in = file.getInputStream()) {
            // 读取 Excel 文件内容
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(this)).sheet().doRead();
        } catch (Exception e) {
            throw new GuLiException(20001, e.getMessage());
        }
    }

    @Override
    public List<SubjectItem> getAllSubjectItems() {
        List<SubjectItem> list = new ArrayList<>();
        // 先获取所有的一级分类
        List<EduSubject> oneSubjects = this.list(
                new LambdaQueryWrapper<EduSubject>()
                        .eq(EduSubject::getParentId, "0"));
        // 对一级分类进行处理
        for (EduSubject oneSub : oneSubjects) {
            SubjectItem oneItem = new SubjectItem().setId(oneSub.getId()).setTitle(oneSub.getTitle());
            // 获取该一级分类的二级分类列表
            List<EduSubject> twoSubjects = this.list(new LambdaQueryWrapper<EduSubject>()
                    .eq(EduSubject::getParentId, oneItem.getId()));
            // 处理二级分类数据
            List<SubjectItem> twoItems = new ArrayList<>();
            for (EduSubject twoSub : twoSubjects) {
                twoItems.add(new SubjectItem(twoSub.getId(), twoSub.getTitle(), null));
            }
            // 将二级分类列表添加到一级分类中
            oneItem.setChildren(twoItems);
            // 将处理好的一级分类放到最终列表中
            list.add(oneItem);
        }
        return list;
    }
}
